import { defineStore } from "pinia";
import { ref } from "vue";
import wsClient from "@/utils/websocket";
import {
  WebSocketMessageType,
  type PrivateMessage,
  type WebSocketMessage,
} from "@/types";
import { ChatSessionType } from "@/types";
import { ElNotification } from "element-plus";
import { useChatSessionStore } from "./useChatSessionStore";
import { createSession } from "@/api/session";
export const useChatStore = defineStore("chat", () => {

  // ==============================状态========================================
  // 当前会话的消息列表
  const currentMessages = ref<PrivateMessage[]>([]);
  // 当前会话的ID
  const currentSessionId = ref<string>("");

  const chatSessionStore = useChatSessionStore();

  // ==============================方法========================================
  // 设置当前会话ID
  const setCurrentSessionId = (sessionId: string) => {
    currentSessionId.value = sessionId;
  };

  // 设置当前会话的消息列表
  const setMessages = (messages: PrivateMessage[]) => {
    currentMessages.value = messages;
  };

  // 添加一条新消息
  const addMessage = (message: PrivateMessage) => {
    currentMessages.value.push(message);
  };

  // 处理新收到的消息
  const handlePrivateMessage = async (message: WebSocketMessage<PrivateMessage>) => {
    const { data } = message;
    // 1. 判断自己当前的会话列表中是否有与消息发送者对应的会话
    // 1.1 如果有，则将消息添加到对应的会话的最新消息
    const session = chatSessionStore.getSessionByTargetId(data.senderId);
    if (session) {
      chatSessionStore.updateLastMessage(session.id, data.content);
      currentMessages.value.push(data);
    }
    // 1.2 如果没有，则创建一个新的会话
    else {
      console.log("创建新的会话");
      const session = await createSession(
        data.senderId,
        ChatSessionType.PRIVATE,
        data.content
      );
      chatSessionStore.insertSession(session.data);
      chatSessionStore.updateLastMessage(session.data.id, data.content);
      currentMessages.value.push(data);
    }
    // 3. 显示通知
    ElNotification({
      title: "收到新消息",
      message: data.content,
      type: "success",
      position: "top-right",
      duration: 3000,
    });
  };

  // 清空消息列表
  const clearMessages = () => {
    currentMessages.value = [];
  };

  // 初始化WebSocket监听
  const initWebSocket = () => {
    wsClient.addMessageHandler(
      WebSocketMessageType.PRIVATE_MSG,
      handlePrivateMessage
    );
  };

  // 清理WebSocket监听
  const cleanupWebSocket = () => {
    wsClient.removeMessageHandler(
      WebSocketMessageType.PRIVATE_MSG,
      handlePrivateMessage
    );
  };

  return {
    currentMessages,
    currentSessionId,
    setCurrentSessionId,
    setMessages,
    addMessage,
    clearMessages,
    initWebSocket,
    cleanupWebSocket,
  };
});
